package com.lxr0860.lxr0860production_test;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.StatFs;
import android.os.SystemClock;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.utils.FileUtils;
import com.lxr0860.lxr0860production_test.utils.PsamControl;
import com.lxr0860.lxr0860production_test.utils.RefreshViewUtils;
import com.lxr0860.lxr0860production_test.utils.ToastUtils;
import com.sdk.devicemanager.Barcode;
import com.sdk.devicemanager.BarcodeConfig;
import com.sdk.devicemanager.LTEcon;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by uniriho on 2018/10/16.
 */

public class LaoHuaActivity extends Activity implements SurfaceHolder.Callback {
    //wifi6000轮；GPS定位30次；条码扫描3000次；后置摄像300次；TF卡测试100轮。
    //wifi相关
    private TextView mTvWifiState;
    private TextView mTvWifiSignal;
    private TextView mTvWifiCount;
    private TextView mTvWifiResult;
    //TF相关
    private TextView mTvTFState;
    private TextView mTvTFMemory;
    private TextView mTvTFCount;
    private TextView mTvTFResult;
    //GPS相关
    private TextView mTvGpsCount;
    private TextView mTvGpsTime;
    private TextView mTvGpsSatellite;
    private TextView mTvGpsLocation;
    private TextView mTvGpsResult;
    //后置摄像
    private SurfaceView mSurfaceView;
    private TextView mTvCameraCount;
    //条码
    private TextView mTvScanCount;
    private TextView mTvScanContent;
    private TextView mTvScanResult;

    private static final double FAIL_PERCENT = 0.1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TF_RESULT:
                    mTvTFCount.setText("第 " + (msg.arg1 + msg.arg2) + " 次");
                    mTvTFResult.setText("成功：" + msg.arg1 + "次|失败：" + msg.arg2 + "次");
                    if (msg.arg1 + msg.arg2 == TF_TEST_COUNT) {
                        if (msg.arg2 > (TF_TEST_COUNT * FAIL_PERCENT)) {
                            mTvTFCount.setText("TF卡测试失败");
                        } else {
                            mTvTFCount.setText("TF卡测试成功");
                            tfComplete = true;
                        }
                    }
                    break;
                case MSG_WIFI_RESULT:
                    mTvWifiResult.setText(
                            "发成功：" + sendSuccessCount + "次 | 失败："
                                    + sendFailCount + "次\n接成功：" + receiveSuccessCount
                                    + "次 | 失败：" + receiveFailCount + "次\n共耗时："
                                    + (wifiTestTime / 1000) + "秒");
                    if ((sendSuccessCount + sendFailCount) == WIFI_TEST_COUNT
                            && (receiveSuccessCount + receiveFailCount) == WIFI_TEST_COUNT) {
                        if (sendFailCount > (WIFI_TEST_COUNT * FAIL_PERCENT) ||
                                receiveFailCount > (WIFI_TEST_COUNT * FAIL_PERCENT)) {
                            mTvWifiCount.setText("wifi测试失败");
                        } else {
                            mTvWifiCount.setText("wifi测试成功");
                            wifiComplete = true;
                        }
                        startGpsTest();
                    }
                    break;
                case MSG_SCAN_RESULT:
                    mTvScanResult.setText("Sam卡成功：" + scanSuccessCount
                            + "次\r\n失败：" + scanFailCount + "次\n"
                            +"单位卡成功：" + scanSuccessCount2
                            + "次\r\n失败：" + scanFailCount2 + "次\n"
                    );
                    if (scanSuccessCount + scanFailCount < SCAN_TEST_COUNT) {
                        mTvScanCount.setText("第" + (scanSuccessCount + scanFailCount + 1) + "次");
                    } else {
                        if (scanFailCount > (SCAN_TEST_COUNT * FAIL_PERCENT)) {
                            mTvScanCount.setText("扫描测试失败");
                        } else {
                            mTvScanCount.setText("扫描测试成功");
                            scanComplete = true;
                        }
                    }
                    break;
                case MSG_GPS_RESULT:
                    mTvGpsTime.setVisibility(View.GONE);
                    mTvGpsSatellite.setText("");
                    mTvGpsResult.setText("成功：" + gpsSuccessCount
                            + "次 | 失败：" + gpsFailCount + "次");
                    if (gpsFailCount > (GPS_TEST_COUNT * FAIL_PERCENT)) {
                        mTvGpsCount.setText("GPS测试失败");
                    } else {
                        mTvGpsCount.setText("GPS测试成功");
                        gpsCompelte = true;
                    }
                    break;
                case MSG_CAMERA_RESULT:
                    Log.e("cly", "MSG_CAMERA_RESULT");
                    isTakePhoto = false;
                    cameraCount++;
                    if (mCamera != null) {
                        if (cameraCount < CAMERA_TEST_COUNT) {
//                            subHandler.post(new Runnable() {
//                                @Override
//                                public void run() {
                            mCamera.startPreview();
//                                }
//                            });
//                            mCamera.startPreview();
                            mTvCameraCount.setText("第" + (cameraCount + 1) + "次拍照");
                        } else if (cameraCount == CAMERA_TEST_COUNT) {
                            mTvCameraCount.setText("测试完毕");
                            cameraComplete = true;
                        }
                    }
                    break;
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", true);
                    mIntent.putExtras(bundle);
                    LaoHuaActivity.this.setResult(Contants.TEST_LAOHUA, mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    finish();
                    break;
            }
            if (wifiComplete && scanComplete && tfComplete && gpsCompelte && cameraComplete) {
                Contants.showDailog(LaoHuaActivity.this, "测试完毕，是否保存结果", this, Gravity.CENTER);
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_laohua);
        initView();
        initData();
    }

    private void initView() {
        mTvWifiState = (TextView) findViewById(R.id.tv_laohua_wifi_state);
        mTvWifiSignal = (TextView) findViewById(R.id.tv_laohua_wifi_signal);
        mTvWifiCount = (TextView) findViewById(R.id.tv_laohua_wifi_test_count);
        mTvWifiResult = (TextView) findViewById(R.id.tv_laohua_wifi_result);

        mTvTFState = (TextView) findViewById(R.id.tv_laohua_tf_state);
        mTvTFMemory = (TextView) findViewById(R.id.tv_laohua_tf_memory);
        mTvTFCount = (TextView) findViewById(R.id.tv_laohua_tf_test_count);
        mTvTFResult = (TextView) findViewById(R.id.tv_laohua_tf_result);

        mTvGpsCount = (TextView) findViewById(R.id.tv_laohua_gps_test_count);
        mTvGpsTime = (TextView) findViewById(R.id.tv_laohua_gps_time);
        mTvGpsSatellite = (TextView) findViewById(R.id.tv_laohua_gps_satellite_count);
        mTvGpsLocation = (TextView) findViewById(R.id.tv_laohua_gps_location_info);
        mTvGpsResult = (TextView) findViewById(R.id.tv_laohua_gps_result);

        mSurfaceView = (SurfaceView) findViewById(R.id.sv_laohua_camera);
        mTvCameraCount = (TextView) findViewById(R.id.tv_laohua_camera_count);

        mTvScanCount = (TextView) findViewById(R.id.tv_laohua_scan_test_count);
        mTvScanContent = (TextView) findViewById(R.id.tv_laohua_scan_content);
        mTvScanResult = (TextView) findViewById(R.id.tv_laohua_scan_result);
    }

    private void initData() {
        File logDir = new File(Contants.LOG_TESTRECORD_PATH);
        Log.d("fileDir", Contants.LOG_FACTORY_PATH);
        if (logDir.exists() && logDir.isFile()) {
            logDir.delete();
        }
        if (!logDir.exists() || !logDir.isDirectory()) {
            logDir.mkdir();
        }

        File file = new File(Contants.LOG_TESTRECORD_PATH, "老化测试" + ".txt");
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //初始化wifi
        initWifi();
        //初始化TF
        initTf();
        //初始化相机
        initCamera();
        //初始化IC
        initIC();
        //初始化GPS
        initGps();

    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyed = true;
        releaseCamera();
        releaseIC();
        releaseWifi();
        releaseTf();
        releaseGps();
    }

    //---------------------wifi-------------------------------
    private WifiManager wifiManager;
    private LTEcon mLtecon;
    private static final int WIFI_TEST_COUNT = 6000;
    private static final int WIFI_STATE_CONNECTED = 1;
    private static final int MSG_WIFI_RESULT = 10;
    private int connectState;
    private Socket socket;
    private int sendSuccessCount, sendFailCount, receiveSuccessCount, receiveFailCount;
    private long wifiTestTime;
    private boolean destroyed, isProcess;
    private WifiThread mWifiThread;
    OutputStream osSend = null;
    InputStream isRead = null;
    private boolean wifiComplete;

    private void initWifi() {
        //关闭4G
        mLtecon = new LTEcon(LaoHuaActivity.this);
        mLtecon.poweroff();
        //wifi
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        registerReceiver(myNetReceiver, filter);//注册监听WIFI连接成功与否
        openWifi();
    }

    private void openWifi() {
        Log.e("cly", "openWifi");
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        } else if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
            connectWifi();
        }
    }

    private void connectWifi() {
        Log.e("cly", "connectWifi");
        wifiManager.startScan();
        WifiConfiguration exitConfig = isMyWifiExit("uniriho");
        if (exitConfig != null) {
            wifiManager.enableNetwork(exitConfig.networkId, true);
        } else {
            WifiConfiguration wifiConfiguration = createWifiInfo("uniriho", "uniriho03");
            wifiManager.enableNetwork(wifiConfiguration.networkId, true);
        }
    }

    private WifiConfiguration isMyWifiExit(String ssid) {
        Log.e("cly", "isMyWifiExit--" + ssid);
        //已配置好的网络
        @SuppressLint("MissingPermission") List<WifiConfiguration> configuredNetworks = wifiManager.getConfiguredNetworks();
        for (WifiConfiguration configuration : configuredNetworks) {
            if (configuration.SSID.equals("\"" + ssid + "\"")) {
                return configuration;
            }
        }
        return null;
    }

    public WifiConfiguration createWifiInfo(String SSID, String Password) {
        Log.e("cly", "createWifiInfo--" + SSID + "--" + Password);
        WifiConfiguration configuration = new WifiConfiguration();
        configuration.allowedAuthAlgorithms.clear();
        configuration.allowedGroupCiphers.clear();
        configuration.allowedKeyManagement.clear();
        configuration.allowedPairwiseCiphers.clear();
        configuration.allowedProtocols.clear();
        configuration.SSID = "\"" + SSID + "\"";
        //wap加密
        configuration.preSharedKey = "\"" + Password + "\"";
        configuration.hiddenSSID = true;
        configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
        configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
        configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
        configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
        configuration.status = WifiConfiguration.Status.ENABLED;
        wifiManager.addNetwork(configuration);
        return configuration;
    }

    private void startWifiTest() {
        Log.e("cly", "startWifiTest");
        if (!isProcess) {
            if (mWifiThread == null) {
                mWifiThread = new WifiThread();
                mWifiThread.start();
            }
        }
    }

    /**
     * WIFI相关监听
     */
    private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {
        @SuppressLint("SetTextI18n")
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(WifiManager.RSSI_CHANGED_ACTION)) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                if (connectState == WIFI_STATE_CONNECTED) {
                    mTvWifiSignal.setText("信号强度为：" + wifiInfo.getRssi());
                }
            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    if (connectState == WIFI_STATE_CONNECTED) {
                        return;
                    }
                    Log.e("cly", "STATE_CHANGED--CONNECTED");
                    connectState = WIFI_STATE_CONNECTED;
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    mTvWifiState.setText("已连接到：" + wifiInfo.getSSID());
                    startWifiTest();
                }
            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int extra = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
                switch (extra) {
                    case WifiManager.WIFI_STATE_ENABLED:
                        Log.e("cly", "WIFI_STATE_ENABLED");
                        mTvWifiState.setText("wifi已打开");
                        connectWifi();
                        break;
                    case WifiManager.WIFI_STATE_DISABLED:
                        Log.e("cly", "WIFI_STATE_DISABLED");
                        mTvWifiState.setText("wifi已关闭");
                        break;
                    case WifiManager.WIFI_STATE_ENABLING:
                        Log.e("cly", "WIFI_STATE_ENABLING");
                        mTvWifiState.setText("正在打开wifi...");
                        break;
                }
            }
        }
    };

    private class WifiThread extends Thread {
        @Override
        public void run() {
            isProcess = true;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (connectServer()) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvWifiCount.setText("连接服务器成功");
                    }
                });
                if (socket != null) {
                    try {
                        //发送
                        String step = "abcdefghijklmnopqrstuvwxy";
                        String receive = "0123456789";
                        String send = null;
                        for (int m = 0; m < 40; m++) {
                            send += step;
                        }
                        final long testStartTime = SystemClock.elapsedRealtime();
                        for (int i = 0; i < WIFI_TEST_COUNT; i++) {
                            if (destroyed) {
                                isProcess = false;
                                return;
                            }
                            RefreshViewUtils.setText(LaoHuaActivity.this, mTvWifiCount,
                                    "第" + (sendSuccessCount + sendFailCount + 1) + "次测试");
                            if (socket.isConnected() && !socket.isClosed()) {
                                if (osSend == null) {
                                    //发送byte字节数据
                                    osSend = socket.getOutputStream();
                                }
                                if (isRead == null) {
                                    isRead = socket.getInputStream();
                                }
                                //写byte字节数据
                                osSend.write(((send + jy(step)).substring(4)).getBytes());
                                //准备接收服务器反馈dateok
                                osSend.flush();
                                String sendResult = "";
                                // 客户端接收服务器端的响应，读取服务器端向客户端的输入流
                                long startSendTime = SystemClock.elapsedRealtime();
                                while (true) {
                                    if (destroyed) {
                                        return;
                                    }
                                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                                        break;
                                    }
                                    if (isRead.available() > 0) {
                                        break;
                                    }
                                }
                                byte[] sendBuf = new byte[isRead.available()];
                                isRead.read(sendBuf);
                                sendResult = new String(sendBuf);
                                if (sendResult.equals("dateok")) {
                                    sendSuccessCount++;
                                } else {
                                    sendFailCount++;
                                }
                            } else {
                                Log.e("cly", "socket异常");
                            }
                            if (socket.isConnected() && !socket.isClosed()) {
                                osSend.write(receive.getBytes());  //写byte字节数据
                                osSend.flush();
                                String receiveRuslt = "";
                                long startSendTime = SystemClock.elapsedRealtime();
                                while (true) {
                                    if (destroyed) {
                                        return;
                                    }
                                    if (SystemClock.elapsedRealtime() - startSendTime >= 3 * 1000) {
                                        break;
                                    }
                                    if (isRead.available() > 0) {
                                        break;
                                    }
                                }
                                byte[] receivebuf = new byte[isRead.available()];
                                isRead.read(receivebuf);
                                receiveRuslt = new String(receivebuf);
                                if (receiveRuslt.length() == 1004) {
                                    receiveSuccessCount++;
                                } else {
                                    receiveFailCount++;
                                }
                            } else {
                                Log.e("cly", "socket异常");
                            }
                            wifiTestTime = SystemClock.elapsedRealtime() - testStartTime;
                            handler.sendEmptyMessage(MSG_WIFI_RESULT);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    isProcess = false;
                }
            } else {
                isProcess = false;
                RefreshViewUtils.setText(LaoHuaActivity.this, mTvWifiCount, "连接服务器失败");
            }
            releaseWifi();
        }
    }

    private boolean connectServer() {
        if (socket == null) {
            socket = new Socket();
        }
        if (socket.isConnected()) {
            return true;
        }
        try {
            socket.connect(new InetSocketAddress("120.79.19.49", 6669), 5000);
            socket.setTcpNoDelay(true);
            socket.setKeepAlive(true);
            return socket.isConnected();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void releaseWifi() {
        if (mWifiThread != null) {
            mWifiThread.interrupt();
            mWifiThread = null;
        }
        if (osSend != null) {
            try {
                osSend.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (isRead != null) {
            try {
                isRead.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (myNetReceiver != null) {
            unregisterReceiver(myNetReceiver);
            myNetReceiver = null;
        }
        if (wifiManager != null) {
            wifiManager.setWifiEnabled(false);
        }
    }

    /**
     * 校验码
     *
     * @param str
     * @return
     */
    public int jy(String str) {
        byte[] bytesB = str.getBytes();
        int sum = 0;//求和
        for (int j = 0; j < 40; j++) {
            for (int i = 0; i < bytesB.length; i++) {
                sum += bytesB[i];
            }
        }
        int jiaoyanma = sum % 10000;//那么和10000取余就可以得到后四位
        if (jiaoyanma < 1000) {//当小于四位数的时候，就每次给他乘以10也就是在末尾添0
            jiaoyanma *= 10;
        }
        return jiaoyanma;
    }


    //-------------------------TF卡---------------------------
    private static final int TF_TEST_COUNT = 1000000;
    private String tfCardPath;
    private static final int NO_TF_CARD = -2;
    private static final int TF_UNMOUNTED = -1;
    private static final int TF_MOUNTED = 0;
    private static final int MSG_TF_RESULT = 11;
    private static final String DIR_PATH = "/lxr";
    private static final String FILE_PATH = "/test.txt";
    private TfThread mTfThread;
    private boolean tfComplete;

    private void initTf() {
        if (mTfThread == null) {
            mTfThread = new TfThread();
            mTfThread.start();
        }
    }

    private class TfThread extends Thread {
        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            switch (getTFCardInfo()) {
                case TF_MOUNTED:
                    final String memory = FileUtils.getGB(tfCardPath);
                    RefreshViewUtils.setText(LaoHuaActivity.this, mTvTFState, "TF卡挂载成功");
                    RefreshViewUtils.setText(LaoHuaActivity.this, mTvTFMemory, memory);
                    break;
                case TF_UNMOUNTED:
                    RefreshViewUtils.setText(LaoHuaActivity.this, mTvTFState, "TF卡挂载失败");
                    return;
                case NO_TF_CARD:
                    RefreshViewUtils.setText(LaoHuaActivity.this, mTvTFState, "未检测到TF卡");
                    return;
            }
            int rightCount = 0;
            int wrongCount = 0;
            for (int i = 0; i < TF_TEST_COUNT; i++) {
                if (destroyed) {
                    return;
                }
                if (testTfCard()) {
                    rightCount++;
                } else {
                    wrongCount++;
                }
                Message msg = Message.obtain();
                msg.arg1 = rightCount;
                msg.arg2 = wrongCount;
                msg.what = MSG_TF_RESULT;
                handler.sendMessage(msg);

            }
        }
    }

    private int getTFCardInfo() {
        int tf_state = NO_TF_CARD;
        StorageManager storageManager = (StorageManager) getApplicationContext()
                .getSystemService(STORAGE_SERVICE);
        StorageVolume[] storageVolumes;
        try {
            Method getVolumeList = StorageManager.class.getDeclaredMethod("getVolumeList");
            storageVolumes = (StorageVolume[]) getVolumeList.invoke(storageManager);
            Method getVolumeState = StorageManager.class
                    .getDeclaredMethod("getVolumeState", String.class);
            for (StorageVolume storageVolume : storageVolumes) {
                String desc = storageVolume.getDescription(this);
                if (desc.contains("SD")) {
                    Method getPath = StorageVolume.class.getMethod("getPath");
                    tfCardPath = (String) getPath.invoke(storageVolume);
                    String state = (String) getVolumeState
                            .invoke(storageManager, tfCardPath);
                    if (Environment.MEDIA_MOUNTED.equals(state)) {
                        tf_state = TF_MOUNTED;
                    } else {
                        tf_state = TF_UNMOUNTED;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tf_state;
    }

    private boolean testTfCard() {
        return FileUtils.creatFile(tfCardPath + DIR_PATH, FILE_PATH)
                && FileUtils.writeDataToTfCard(tfCardPath + DIR_PATH + FILE_PATH)
                && FileUtils.copyFile(tfCardPath + DIR_PATH + FILE_PATH,
                tfCardPath + DIR_PATH + "/newfile.log")
                && FileUtils.deleteFile(tfCardPath + DIR_PATH);
    }

    private void releaseTf() {
        if (mTfThread != null) {
            mTfThread.interrupt();
            mTfThread = null;
        }
        if (handler != null) {
            handler.removeMessages(MSG_TF_RESULT);
        }
    }


    //-------------------------扫描------------------------------
    private static final int SCAN_TEST_COUNT = 1000000;

    private int scanSuccessCount, scanFailCount;
    private int scanSuccessCount2, scanFailCount2;
    private static final int MSG_SCAN_RESULT = 13;
    private boolean scanComplete;


    private void initIC() {

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startICTest();
            }
        }, 1000);

    }

    private void startICTest() {
        mTvScanCount.setText("IC卡第" + (scanSuccessCount + scanFailCount + 1) + "次测试");
        new ScanThread().start();
    }

    private class ScanThread extends Thread {
        @Override
        public void run() {

            int open = PsamControl.ICC_interface_power(1);
            if (open!=0) {
                RefreshViewUtils.setText(LaoHuaActivity.this, mTvScanCount, "IC上电失败");
                return;
            }
            RefreshViewUtils.setText(LaoHuaActivity.this, mTvScanCount, "IC上电成功");
            boolean isSam = false;
            for (int i = 1; i < SCAN_TEST_COUNT; i++) {

                if (destroyed) {
                    return;
                }
                if (i%2==0) {
                    //选择sam卡
                    isSam = true;
                    PsamControl.ICC_select_sock(1);
                }else{
                    //选择单位卡
                    isSam = false;
                    PsamControl.ICC_select_sock(2);
                }

                //sam卡复位
                PsamControl.ICC_cpucard_ATR(new PsamControl.ICCTPDUDataListener() {
                    @Override
                    public void ICCResponseDataCallback(int status, String data, int dataLen, String statusCode) {
//                        if (status == 0) {
//                            scanSuccessCount++;
//                        } else {
//                            scanFailCount++;
//                        }
                    }
                });
                //sam卡随机数
                boolean finalIsSam = isSam;
                PsamControl.ICC_T0_TPDU_RandomData(new PsamControl.ICCTPDUDataListener() {
                    @Override
                    public void ICCResponseDataCallback(int status, String data, int dataLen, String statusCode) {
                        if (status == 0) {
                            if (finalIsSam) {
                                scanSuccessCount++;
                            }else{
                                scanSuccessCount2++;
                            }
                        } else {
                            if (finalIsSam) {
                                scanFailCount++;
                            }else {
                                scanFailCount2++;
                            }
                        }
                    }
                });
                handler.sendEmptyMessage(MSG_SCAN_RESULT);
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            int close = PsamControl.ICC_interface_power(0);
            if (close!=0) {
                RefreshViewUtils.appendText(LaoHuaActivity.this, mTvScanCount, "IC下电失败");
                return;
            }
            RefreshViewUtils.appendText(LaoHuaActivity.this, mTvScanCount, "IC下电成功");
        }
    }


    private void releaseIC() {
        if (handler != null) {
            handler.removeMessages(MSG_SCAN_RESULT);
        }
        PsamControl.ICC_interface_power(0);
    }


    //---------------------------GPS---------------------------------
    private static final String GPS_TAG = "gps";
    private static final int GPS_TEST_COUNT = 30000000;
    private static final int MSG_GPS_RESULT = 12;
    private LocationManager mLocationManager;
    private boolean firstLocate;
    private int gpsSuccessCount, gpsFailCount;
    private int gpsTimeout;
    private boolean gpsCompelte;

    private void initGps() {
        mTvGpsTime.setVisibility(View.GONE);
        mTvGpsCount.setText("待WIFI测试完毕开始GPS测试");
        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }

    @SuppressLint("MissingPermission")
    private void startGpsTest() {
        if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            mLocationManager.registerGnssStatusCallback(mStatusListener);
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
                    0, mLocationListener);
        } else {
            openOrCloseGps(true);
        }
    }

    @SuppressLint("MissingPermission")
    private void openOrCloseGps(boolean enable) {
        if (enable) {
            //打开GPS
            if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                try {
                    mTvGpsLocation.setText("定位启动");
                    Settings.Secure.setLocationProviderEnabled(LaoHuaActivity.this.
                            getContentResolver(), LocationManager.GPS_PROVIDER, true);
                    mLocationManager.registerGnssStatusCallback(mStatusListener);
                    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000,
                            0, mLocationListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            //关闭GPS
            if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                try {
                    Settings.Secure.setLocationProviderEnabled(LaoHuaActivity.this.
                            getContentResolver(), LocationManager.GPS_PROVIDER, false);
                    mLocationManager.removeUpdates(mLocationListener);
                    mLocationManager.unregisterGnssStatusCallback(mStatusListener);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     * GPS定位监听
     */
    private LocationListener mLocationListener = new LocationListener() {
        //GPS状态变化时触发
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
                //GPS状态为可见时
                case LocationProvider.AVAILABLE:
//                    Log.e(TAG, "当前GPS状态为可见状态");
                    break;
                //GPS状态为服务区外时
                case LocationProvider.OUT_OF_SERVICE:
//                    Log.e(TAG, "当前GPS状态为服务区外状态");
                    break;
                //GPS状态为暂停服务时
                case LocationProvider.TEMPORARILY_UNAVAILABLE:
//                    Log.e(TAG, "当前GPS状态为暂停服务状态");
                    break;
            }
        }

        //GPS开启时触发
        @Override
        public void onProviderEnabled(String provider) {
            Log.e(GPS_TAG, "onProviderEnabled");
            mTvGpsLocation.setText("定位启动");
        }

        //GPS禁用时触发
        @Override
        public void onProviderDisabled(String provider) {
            Log.e(GPS_TAG, "onProviderDisabled");
            firstLocate = false;
        }

        //位置信息变化时触发
        @Override
        public void onLocationChanged(Location location) {
            Log.e(GPS_TAG, "onLocationChanged");
            if (firstLocate) {
                Log.e("cly", "定位成功");
                handler.removeCallbacks(gpsRepeatRunnable);
//                handler.removeCallbacks(gpsRunnable);
                updateView(location);
            } else {
                Log.e("cly", "首次清除星历");
                mLocationManager.sendExtraCommand(
                        LocationManager.GPS_PROVIDER,
                        "delete_aiding_data", null);
                mTvGpsCount.setText("首次清除星历");
                gpsTimeout = 0;
                handler.postDelayed(gpsRepeatRunnable, 1000);
//                handler.postDelayed(gpsRunnable,1000);
            }
        }
    };


    /**
     * GPS状态监听
     */

    private GnssStatus.Callback mStatusListener = new GnssStatus.Callback() {
        @Override
        public void onStarted() {
            super.onStarted();
        }

        @Override
        public void onStopped() {
            super.onStopped();
        }

        @Override
        public void onFirstFix(int ttffMillis) {
            super.onFirstFix(ttffMillis);
            Log.e(GPS_TAG, "第一次定位");
            firstLocate = true;
        }

        @Override
        public void onSatelliteStatusChanged(@NonNull GnssStatus status) {
            super.onSatelliteStatusChanged(status);

            //获取卫星颗数的默认最大值
            int maxSatellites = status.getSatelliteCount();
            int usedCount = 0;//有效卫星个数

            List<Float> mSnrf = new ArrayList<>();
            List<String> indexs = new ArrayList<>();

            for (int i = 0; i < maxSatellites; i++) {
                int svid = status.getSvid(i);
                float cn0DbHz = status.getCn0DbHz(i);
                if (cn0DbHz > -1.0 && mSnrf.size() < 20) {
                    mSnrf.add(cn0DbHz);//信号强度
                    indexs.add(String.valueOf(svid));
                }
                if (status.usedInFix(i)) {
                    usedCount++;
                    Log.e("SNR：", svid
                            + "号有效卫星信号强度：" + cn0DbHz);
                }
            }
            mTvGpsSatellite.setText("卫星总个数:" + maxSatellites + ",有效个数:" + usedCount);
        }
    };

    /**
     * 更新位置信息
     *
     * @param location
     */
    private void updateView(Location location) {
        if (location != null) {
            Log.e("cly", "lng=" + location.getLongitude() + "--lat=" + location.getLatitude());
            mTvGpsLocation.setText("经度：" + location.getLongitude()
                    + "\r\n纬度：" + location.getLatitude());
            if (gpsTimeout <= 60) {
                handler.removeCallbacks(gpsRepeatRunnable);
                gpsSuccessCount++;
                mTvGpsCount.setText("第" + (gpsFailCount + gpsSuccessCount) + "次定位");
                if ((gpsFailCount + gpsSuccessCount) < GPS_TEST_COUNT) {
                    mLocationManager.sendExtraCommand(
                            LocationManager.GPS_PROVIDER,
                            "delete_aiding_data", null);
                    mTvGpsLocation.setText("正在定位...");
                    gpsTimeout = 0;
                    handler.postDelayed(gpsRepeatRunnable, 1000);
                } else {
                    releaseGps();
                    handler.removeCallbacks(gpsRepeatRunnable);
                    handler.sendEmptyMessage(MSG_GPS_RESULT);
                }
            }
        }
    }

    Runnable gpsRepeatRunnable = new Runnable() {
        @Override
        public void run() {
            gpsTimeout++;
            handler.postDelayed(this, 1000);
            if (gpsTimeout > 60) {
                gpsFailCount++;
                mTvGpsCount.setText("第" + (gpsFailCount + gpsSuccessCount) + "次");
                mTvGpsTime.setText("定位超时");
                handler.removeCallbacks(gpsRepeatRunnable);
                if ((gpsFailCount + gpsSuccessCount) == GPS_TEST_COUNT) {
                    releaseGps();
                    handler.removeCallbacks(gpsRepeatRunnable);
                    handler.sendEmptyMessage(MSG_GPS_RESULT);
                } else {
                    mLocationManager.sendExtraCommand(
                            LocationManager.GPS_PROVIDER,
                            "delete_aiding_data", null);
                    mTvGpsLocation.setText("正在定位...");
                    gpsTimeout = 0;
                    handler.postDelayed(gpsRepeatRunnable, 1000);
                }
            } else {
                mTvGpsCount.setText("第" + (gpsFailCount + gpsSuccessCount + 1) + "次");
                mTvGpsTime.setVisibility(View.VISIBLE);
                mTvGpsTime.setText(gpsTimeout + "秒");
            }
        }
    };

    private void releaseGps() {
        handler.removeCallbacks(gpsRepeatRunnable);
        if (mLocationManager != null) {
            mLocationManager.removeUpdates(mLocationListener);
            mLocationManager.unregisterGnssStatusCallback(mStatusListener);
            openOrCloseGps(false);
        }
    }


    //-----------------------------camera---------------------------------
    private static final int CAMERA_TEST_COUNT = 15000;
    private static final int MSG_CAMERA_RESULT = 14;
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private int mCameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
    private int cameraCount;
    private boolean isTakePhoto;
    private static final String SAVEPATH = Environment
            .getExternalStorageDirectory() + File.separator + "laohua_photo";
    private String picturePath;
    private boolean cameraComplete;
    private HandlerThread mHandlerThread;
    private Handler subHandler;

    private void initCamera() {
        if (!Contants.hasCamera(this)) {
            mTvCameraCount.setText("不支持相机");
            return;
        }
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mHandlerThread = new HandlerThread("my_handlerthread");
        mHandlerThread.start();
        subHandler = new Handler(mHandlerThread.getLooper());
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.e("cly", "surfaceCreated");
        try {
            mTvCameraCount.setText("第" + (cameraCount + 1) + "次拍照");
//            subHandler.post(new Runnable() {
//                @Override
//                public void run() {
            openCamera();
            if (mHolder.getSurface() == null) {
                System.out.println("surfaceChanged:mHolder.getSurface() == null");
                return;
            }
            try {
                mCamera.stopPreview();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                mCamera.startPreview();
//                        mTvCameraCount.setText("第" + (cameraCount + 1) + "次拍照");
                //相机startPriview以后会启用这个回调，在这里面设置是否可以聚焦和是否可以拍照
                mCamera.setPreviewCallback(new Camera.PreviewCallback() {
                    @Override
                    public void onPreviewFrame(byte[] data, Camera camera) {
                        // TODO Auto-generated method stub
//                    Log.e("cly", "预览onPreviewFrame");
                        takePhoto();

                        if (mCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
                            subHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    mCamera.autoFocus(focusCallback);
                                }
                            });
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
//                }
//            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0) {
        Log.e("cly", "surfaceDestroyed");
        releaseCamera();
    }


    // 开始预览相机
    public void openCamera() {
        Log.e("cly", "openCamera-->" + Thread.currentThread().getName());
        try {
            if (mCamera == null) {
                mCamera = getCameraInstance();
                mCamera.enableShutterSound(false);
                Camera.Parameters parameters = mCamera.getParameters();
                parameters.setRecordingHint(true);
                {
                    //设置获取数据
                    parameters.setPreviewFormat(ImageFormat.NV21);
                    //parameters.setPreviewFormat(ImageFormat.YUV_420_888);

                    //通过setPreviewCallback方法监听预览的回调
                    mCamera.setPreviewCallback(new Camera.PreviewCallback() {
                        @Override
                        public void onPreviewFrame(byte[] bytes, Camera camera) {
                            //这里面的Bytes的数据就是NV21格式的数据,或者YUV_420_888的数据
                        }
                    });
                }

                if (mCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
                    parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                }
                mCamera.setParameters(parameters);
                mCamera.setPreviewDisplay(mHolder);
                Log.e("cly", "相机打开成功");
                setCameraDisplayOrientation(this, mCameraId, mCamera);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("cly", "相机打开失败");
        }
    }

    // 获取相机实例
    public Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open(mCameraId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }

    //拍照
    private void takePhoto() {
        Log.e("cly", "takePhoto-->" + isTakePhoto);
        if (isTakePhoto) {
            return;
        }
        isTakePhoto = true;
        if (mCamera != null) {
            if (!(getMemonry() > 5 * 1024 * 1024)) {
                ToastUtils.showMessage("内存已不足5M");
                return;
            }
            subHandler.post(new Runnable() {
                @Override
                public void run() {
                    mCamera.takePicture(null, null, mPictureCallback);
                }
            });
        }
    }

    private Camera.AutoFocusCallback focusCallback = new Camera.AutoFocusCallback() {
        @Override
        public void onAutoFocus(boolean success, Camera camera) {
            if (success) {
                subHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        takePhoto();
                    }
                }, 100);
            }
        }
    };

    // 拍照回调
    private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
        public void onPictureTaken(final byte[] data, Camera camera) {
            Log.e("cly", "mPictureCallback-->" + Thread.currentThread().getName());
            File dir = new File(SAVEPATH);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            picturePath = SAVEPATH
                    + File.separator
                    + new DateFormat().format("yyyyMMddHHmmss", new Date())
                    .toString() + ".jpg";
            new Thread(new Runnable() {
                public void run() {
                    BufferedOutputStream bos = null;
                    Bitmap bitmap = null;
                    File file = new File(picturePath);
                    try {
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        bitmap = BitmapFactory.decodeByteArray(data, 0,
                                data.length);
                        bitmap = rotateBitmapByDegree(bitmap, 90);
                        bos = new BufferedOutputStream(
                                new FileOutputStream(file));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                        bos.flush();
                        bos.close();
                        bitmap.recycle();
                        handler.sendEmptyMessage(MSG_CAMERA_RESULT);
                        scanPhoto(picturePath);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (bos != null) {
                            try {
                                bos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if (bitmap != null) {
                            bitmap.recycle();
                        }
                    }
                }
            }).start();
        }
    };

    // 旋转图片
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        try {
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    // 设置相机横竖屏
    public void setCameraDisplayOrientation(Activity activity, int cameraId,
                                            Camera camera) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }
        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;
        } else {
            result = (info.orientation - degrees + 360) % 360;
        }
        Log.e("cly", "oretation=" + result);
        camera.setDisplayOrientation(result);
    }

    // 释放相机
    public void releaseCamera() {
//        if(mHandlerThread!=null){
//            mHandlerThread.interrupt();
//            mHandlerThread=null;
//        }
//        if(subHandler!=null){
//            subHandler.removeCallbacks(null);
//        }
        handler.removeMessages(MSG_CAMERA_RESULT);
        isTakePhoto = false;
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
    }

    private void scanPhoto(String path) {
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(path))));
    }

    /**
     * 获取剩余可用内存
     *
     * @return
     */
    private long getMemonry() {
        StatFs statFs = new StatFs(Environment.getDataDirectory().getPath());
        long size = statFs.getAvailableBytes();
        return size;
    }
}

